#!/bin/bash

# Diawi自动化上传脚本
# 用于打包Flutter应用并上传到Diawi平台

set -e

# 配置
DIAWI_TOKEN="z1EH0NMJgFBt9wKES8UYny1PlxpVvczVriqrf1Scv6"
PROJECT_NAME="flutter_ai_base"
VERSION=$(grep "version:" pubspec.yaml | sed 's/version: //' | tr -d ' ')

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查依赖
check_dependencies() {
    print_info "检查依赖..."
    
    if ! command -v flutter &> /dev/null; then
        print_error "Flutter 未安装或不在 PATH 中"
        exit 1
    fi
    
    if ! command -v curl &> /dev/null; then
        print_error "curl 未安装"
        exit 1
    fi
    
    if ! command -v jq &> /dev/null; then
        print_warning "jq 未安装，建议安装以获得更好的JSON解析体验"
    fi
    
    print_success "依赖检查完成"
}

# 检查是否为Flutter项目
check_flutter_project() {
    if [ ! -f "pubspec.yaml" ]; then
        print_error "当前目录不是Flutter项目"
        exit 1
    fi
    print_success "Flutter项目检测成功"
}

# 清理构建
clean_build() {
    print_info "清理之前的构建..."
    flutter clean
    flutter pub get
    print_success "清理完成"
}

# 构建Android APK
build_android() {
    print_info "开始构建Android APK..."
    
    # 构建release版本
    flutter build apk --release --target-platform android-arm64
    
    if [ $? -eq 0 ]; then
        APK_PATH="build/app/outputs/flutter-apk/app-release.apk"
        if [ -f "$APK_PATH" ]; then
            print_success "Android APK构建成功: $APK_PATH"
            return 0
        else
            print_error "APK文件未找到"
            return 1
        fi
    else
        print_error "Android构建失败"
        return 1
    fi
}

# 构建iOS IPA (需要macOS)
build_ios() {
    if [[ "$OSTYPE" != "darwin"* ]]; then
        print_warning "当前系统不是macOS，跳过iOS构建"
        return 1
    fi
    
    print_info "开始构建iOS IPA..."
    
    # 检查是否有iOS项目
    if [ ! -d "ios" ]; then
        print_warning "iOS目录不存在，跳过iOS构建"
        return 1
    fi
    
    # 构建iOS
    flutter build ios --release --no-codesign
    
    if [ $? -eq 0 ]; then
        print_success "iOS构建成功"
        
        # 创建IPA包
        IPA_DIR="build/ios/iphoneos"
        APP_PATH="$IPA_DIR/Runner.app"
        IPA_PATH="build/ios/flutter_ai_base.ipa"
        
        if [ -d "$APP_PATH" ]; then
            # 创建Payload目录并打包IPA
            mkdir -p "build/ios/Payload"
            cp -R "$APP_PATH" "build/ios/Payload/"
            cd "build/ios"
            zip -r "flutter_ai_base.ipa" "Payload"
            cd "../.."
            
            if [ -f "$IPA_PATH" ]; then
                print_success "IPA打包成功: $IPA_PATH"
                return 0
            else
                print_error "IPA打包失败"
                return 1
            fi
        else
            print_error "Runner.app文件未找到"
            return 1
        fi
    else
        print_error "iOS构建失败"
        return 1
    fi
}

# 上传文件到Diawi
upload_to_diawi() {
    local file_path=$1
    local platform=$2
    local comment="$platform build - Version: $VERSION - $(date '+%Y-%m-%d %H:%M:%S')"
    
    print_info "上传 $platform 应用到 Diawi..."
    print_info "文件路径: $file_path"
    
    # 检查文件是否存在
    if [ ! -f "$file_path" ]; then
        print_error "文件不存在: $file_path"
        return 1
    fi
    
    # 获取文件大小
    file_size=$(ls -lh "$file_path" | awk '{print $5}')
    print_info "文件大小: $file_size"
    
    # 上传到Diawi
    print_info "正在上传，请稍候..."
    
    response=$(curl -s -X POST \
        -F "token=$DIAWI_TOKEN" \
        -F "file=@$file_path" \
        -F "comment=$comment" \
        -F "callback_emails=" \
        -F "password=" \
        -F "wall_of_apps=false" \
        "https://upload.diawi.com/")
    
    # 检查响应
    if [ $? -ne 0 ]; then
        print_error "上传请求失败"
        return 1
    fi
    
    # 解析响应
    if command -v jq &> /dev/null; then
        job_id=$(echo "$response" | jq -r '.job // empty')
        if [ -n "$job_id" ] && [ "$job_id" != "null" ]; then
            print_success "上传成功，任务ID: $job_id"
            check_upload_status "$job_id" "$platform"
        else
            error_msg=$(echo "$response" | jq -r '.message // "未知错误"')
            print_error "上传失败: $error_msg"
            echo "完整响应: $response"
            return 1
        fi
    else
        # 没有jq时的简单解析
        if echo "$response" | grep -q '"job"'; then
            job_id=$(echo "$response" | sed -n 's/.*"job":"\([^"]*\)".*/\1/p')
            print_success "上传成功，任务ID: $job_id"
            check_upload_status "$job_id" "$platform"
        else
            print_error "上传失败"
            echo "响应: $response"
            return 1
        fi
    fi
}

# 检查上传状态
check_upload_status() {
    local job_id=$1
    local platform=$2
    local max_attempts=30
    local attempt=1
    
    print_info "检查 $platform 应用处理状态..."
    
    while [ $attempt -le $max_attempts ]; do
        print_info "检查状态 ($attempt/$max_attempts)..."
        
        status_response=$(curl -s "https://upload.diawi.com/status?token=$DIAWI_TOKEN&job=$job_id")
        
        if command -v jq &> /dev/null; then
            status=$(echo "$status_response" | jq -r '.status // "unknown"')
            
            case $status in
                2000)
                    # 处理完成
                    link=$(echo "$status_response" | jq -r '.link // "未获取到链接"')
                    qr_code=$(echo "$status_response" | jq -r '.qrcode // ""')
                    
                    print_success "🎉 $platform 应用处理完成！"
                    echo ""
                    echo "========================================="
                    echo "📱 $platform 应用安装信息"
                    echo "========================================="
                    echo "🔗 安装链接: $link"
                    echo "📱 二维码: $qr_code"
                    echo "📝 版本: $VERSION"
                    echo "⏰ 上传时间: $(date '+%Y-%m-%d %H:%M:%S')"
                    echo "========================================="
                    echo ""
                    
                    # 保存链接到文件
                    echo "$link" >> "diawi_links.txt"
                    echo "链接已保存到 diawi_links.txt"
                    
                    return 0
                    ;;
                4000)
                    error_msg=$(echo "$status_response" | jq -r '.message // "处理失败"')
                    print_error "$platform 应用处理失败: $error_msg"
                    return 1
                    ;;
                *)
                    # 仍在处理中
                    sleep 10
                    ;;
            esac
        else
            # 没有jq时的简单检查
            if echo "$status_response" | grep -q '"status":2000'; then
                link=$(echo "$status_response" | sed -n 's/.*"link":"\([^"]*\)".*/\1/p')
                print_success "🎉 $platform 应用处理完成！"
                echo "🔗 安装链接: $link"
                echo "$link" >> "diawi_links.txt"
                return 0
            elif echo "$status_response" | grep -q '"status":4000'; then
                print_error "$platform 应用处理失败"
                echo "响应: $status_response"
                return 1
            else
                sleep 10
            fi
        fi
        
        ((attempt++))
    done
    
    print_error "$platform 应用处理超时"
    return 1
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -a, --android    仅构建并上传Android应用"
    echo "  -i, --ios        仅构建并上传iOS应用"
    echo "  -c, --clean      执行flutter clean"
    echo "  -h, --help       显示此帮助信息"
    echo ""
    echo "如果不指定平台，将尝试构建所有支持的平台"
}

# 主函数
main() {
    local build_android=false
    local build_ios=false
    local clean_first=false
    
    # 解析命令行参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -a|--android)
                build_android=true
                shift
                ;;
            -i|--ios)
                build_ios=true
                shift
                ;;
            -c|--clean)
                clean_first=true
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                print_error "未知选项: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    # 如果没有指定平台，默认构建所有支持的平台
    if [ "$build_android" = false ] && [ "$build_ios" = false ]; then
        build_android=true
        build_ios=true
    fi
    
    print_info "🚀 Flutter应用自动化上传到Diawi"
    print_info "项目: $PROJECT_NAME"
    print_info "版本: $VERSION"
    echo ""
    
    # 检查环境
    check_dependencies
    check_flutter_project
    
    # 清理构建
    if [ "$clean_first" = true ]; then
        clean_build
    fi
    
    # 构建和上传
    local success_count=0
    local total_count=0
    
    if [ "$build_android" = true ]; then
        ((total_count++))
        if build_android; then
            upload_to_diawi "build/app/outputs/flutter-apk/app-release.apk" "Android"
            if [ $? -eq 0 ]; then
                ((success_count++))
            fi
        fi
    fi
    
    if [ "$build_ios" = true ]; then
        ((total_count++))
        if build_ios; then
            upload_to_diawi "build/ios/flutter_ai_base.ipa" "iOS"
            if [ $? -eq 0 ]; then
                ((success_count++))
            fi
        fi
    fi
    
    # 总结
    echo ""
    echo "========================================="
    echo "📊 上传总结"
    echo "========================================="
    echo "✅ 成功: $success_count/$total_count"
    
    if [ -f "diawi_links.txt" ]; then
        echo "📋 所有安装链接已保存到: diawi_links.txt"
    fi
    
    if [ $success_count -eq $total_count ] && [ $total_count -gt 0 ]; then
        print_success "🎉 所有应用上传成功！"
        exit 0
    else
        print_warning "⚠️  部分应用上传失败"
        exit 1
    fi
}

# 运行主函数
main "$@" 